﻿/**
* CRL
*/
#if NETSTANDARD
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using CRL.Core.Remoting;
using System.Data;
using CRL.Transaction.DbStatus;

#endif
namespace CRL.Transaction.NetCore
{
#if NETSTANDARD
    public static class TransControlExtensions
    {
        public static void AddTransControl(this IServiceCollection services, params Assembly[] assemblies)
        {
            services.AddTransient<SagaControl>();
            services.AddTransient<TccControl>();
            //services.AddScoped<DbStatus.ITransInfoManage, T>();
            services.AddSingleton<TransLoader>();
            foreach (var assembyle in assemblies)
            {
                var types = assembyle.GetTypes();
                foreach (var type in types)
                {
                    if (type == typeof(CustomSagaStep))
                    {
                        continue;
                    }
                    if (type == typeof(CustomTccStep))
                    {
                        continue;
                    }
                    if (typeof(IStep).IsAssignableFrom(type) && !type.IsAbstract)
                    {
                        var implementedInterface = ServerCreater.GetImplementedInterface(type);
                        if (implementedInterface == null)
                        {
                            services.AddTransient(type);
                        }
                        else
                        {
                            services.AddTransient(implementedInterface, type);
                        }
                    }
                    else if (typeof(DbStatus.ITransInfoManage).IsAssignableFrom(type) && !type.IsAbstract)
                    {
                        services.AddTransient(typeof(DbStatus.ITransInfoManage), type);
                    }
                }
            }
        }

        public static void UseTransControl(this IApplicationBuilder app, string projectName)
        {
            var provider = app.ApplicationServices;
            var host = provider.GetService<IHost>();
            if (host == null)
            {
                throw new Exception("δ�ܻ�ȡ��IHost �Ƿ�ΪASP.NET Core 3?");
            }
            TransConfig._manageFunc = () => host.Services.GetService<ITransInfoManage>();
            var loader = provider.GetService<TransLoader>();
            loader.StartCheckThread(projectName);
        }
    }

#endif
}
